package com.cn.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.UUID;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtils {

	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	
	private static DataSource dataSource;
		
		
	static{
		dataSource = new ComboPooledDataSource();
	}
	public static Connection getConnectionWithTransaction(){
		Connection conn = tl.get();
		if(conn==null){
			try {
				conn = dataSource.getConnection();
				tl.set(conn);
				conn.setAutoCommit(false);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return conn;
	}
	
	public static void commit(){
		Connection con = tl.get();
		if(con!=null){
			try {
				con.commit();
				tl.remove();//
				con.close();	
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public static void rollback(){
		Connection con = tl.get();
		if(con!=null){
			try {
				con.rollback();
				tl.remove();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException("数据库连接失败");
		}
	}
	public static void close(ResultSet rs,Statement st,Connection con){
		
			try {
				if(rs!=null){
					rs.close();
				}
				if(st!=null){
					st.close();
				}
				if(con!=null){
					con.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	public static void main(String[] args) {
		
		
	}
}
